<template>
  <div class="page-modal">
    <el-dialog
      center
      width="50%"
      title="新建用户"
      destroy-on-close
      v-model="showModal">
      <art-form v-bind="modalConfig" v-model="formData"></art-form>
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="e => showModal = !showModal">取消</el-button>
          <el-button type="primary" @click="handleConfirmClick">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from "vue";

import { useStore } from '@/store'

import ArtForm from "@/base-ui/form/index";

export default defineComponent({
  components: {
    ArtForm,
  },
  props: {
    modalConfig: {
      type: Object,
      default: () => ({}),
    },
    defaultInfo: {
      type: Object,
      default: () => ({})
    },
    pageName: {
      type: String,
      required: true
    },
    otherInfo: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props) {
    const showModal = ref(false);
    const formData = ref<any>({})

    watch(() => props.defaultInfo, 
      newValue => {
        for (const item of props.modalConfig.formItems) {
          formData.value[`${item.field}`] = newValue[`${item.field}`]
        }
      }
    )

    const store = useStore()
    const handleConfirmClick = () => {
      showModal.value = false
      if (Object.keys(props.defaultInfo).length) {
        // 编辑
        store.dispatch('system/editPageTableListAction', {
          pageName: props.pageName,
          queryInfo: { ...formData.value, ...props.otherInfo },
          id: props.defaultInfo.id
        })
      } else {
        store.dispatch('system/createPageTableListAction', {
          pageName: props.pageName,
          queryInfo: { ...formData.value, ...props.otherInfo },
        })
      }
    }

    return {
      showModal,
      formData,
      handleConfirmClick
    };
  },
});
</script>

<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>